package com.tanhua.admin.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.sso.admin.Admin;
import com.tanhua.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //登录
    public Map login(String username, String password, String verificationCode, String uuid) {
        //校验验证码
        String code = redisTemplate.opsForValue().get(uuid);
        if (!StrUtil.equals(code,verificationCode)){
            throw new BusinessException("验证码校验失败");
        }
        //md5加密
        String md5Password = SecureUtil.md5(password);
        //查看数据库判断用户是否存在
        LambdaQueryWrapper<Admin> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername,username).eq(Admin::getPassword,md5Password);
        Admin admin = adminMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtil.isEmpty(admin)){
            throw new BusinessException("用户名或密码不正确");
        }
        //删除验证码
        redisTemplate.delete(uuid);
        Map map=new HashMap<>();
        map.put("username",username);
        map.put("id",admin.getId());
        //生成token
        String token = JwtUtils.getToken(map);
        Map newMap=new HashMap();
        newMap.put("token",token);
        return newMap;
    }

    /*用户基本信息*/
    public Map profile() {
        Map map=new HashMap();
        //获取当前用户id
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        if (ObjectUtil.isEmpty(admin)){
            throw new BusinessException("查无信息");
        }
        map.put("avatar",admin.getAvatar());
        map.put("id",userId);
        map.put("username",admin.getUsername());
        return map;
    }
}
